package jug.lodz.concurrency;

import java.util.Random;

//http://pveentjer.wordpress.com/2008/10/30/volatile-arrays/
public class Loop1 {
	boolean complete = false;
//	boolean[] completeArr = new boolean[]{false, false, false};

	
	public static void main(String[] args) throws Exception {
		Loop1 loop = new Loop1();
		Thread t = loop.spawnNewThread();
		
		t.start();
		Thread.sleep(1000);
		
		loop.complete();

		System.out.println("tMain " + loop.isComplete());
		t.join();
	}

	private Thread spawnNewThread() {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				boolean toggle = false;
				while (!isComplete()) {
					toggle = !toggle;
//					System.out.println(isComplete());
				}
				System.out.println("t2 " + isComplete());
			}
		});
		
		return t;
	}


	private boolean isComplete() {
//		synchronized(Loop1.class) { }//does the monitor.lock
		return complete;

//		for (boolean b : completeArr) {
//			if (b == false)
//				return false; 
//		}
//		return true;
//		return completeArr[1];
	}


	private void complete() {
//		for (int i = 0; i < completeArr.length; i++) {
//			completeArr[i] = true;
//		}
		complete = true;
//		synchronized(Loop1.class) { }//does the monitor.unlock
	}

}
